import Vue from 'vue'
import VueRouter from 'vue-router'
const Login = ()=>import('../views/Login.vue')
const Layout = ()=>import('../views/Layout.vue')
const Menu = ()=>import('../views/menu/index.vue')
const Role = ()=>import('../views/role/index.vue')
const User = ()=>import('../views/user/index.vue')
const Category = ()=>import('../views/category/index.vue')
const Specs = ()=>import('../views/specs/index.vue')
const Goods = ()=>import('../views/goods/index.vue')
const Index = ()=>import('../views/index.vue')
// 引入store，获取登录状态
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login,
    meta: {
      title: '欢迎登录'
    }
  },
  {
    path: '/',
    component: Layout,
    // 以上是父路由
    // 以下是子路由，都是路由对象
    children: [
      {
        path: '/',
        component: Index
      },
      {
        path: '/menu',
        component: Menu
      },
      {
        path: '/role',
        component: Role
      },
      {
        path: '/user',
        component: User
      },
      {
        path: '/category',
        component: Category
      },
      {
        path: '/specs',
        component: Specs
      },
      {
        path: '/goods',
        component: Goods
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局前置守卫，需求：未登录时只能查看login和index页面
router.beforeEach((to, from, next)=>{
  // 是否登录
  if(store.state.userInfo.token) {
    // 已登录,可以看所有页面
    next()
  }else {
    // 未登录时只能查看login和index页面
    if(to.path === '/login' || to.path === '/') {
      next()
    }else {
      // 先登录
      router.push('/login')
    }
  }
})

export default router
